package org.example.learn.javaagent.apply_demo.plugin.impl.jvm;

import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;
import java.util.Arrays;
import java.util.List;

// 获取JVM内存和GC信息
public class JVMStack {

    private static final long MB = 1048576L;

    // 打印JVM内存信息
    public static void printMemoryInfo(){
        MemoryMXBean memory = ManagementFactory.getMemoryMXBean();

        System.out.println("headMemory");
        MemoryUsage headMemory = memory.getHeapMemoryUsage();
        String info = String.format("init：%s\t max: %s\t used: %s\t committed: %s\t use rate: %s",
                headMemory.getInit() / MB + "MB",
                headMemory.getMax() / MB + "MB",
                headMemory.getUsed() / MB + "MB",
                headMemory.getCommitted() / MB + "MB",
                headMemory.getUsed() * 100 / headMemory.getCommitted() + "%");
        System.out.println(info);

        System.out.println("nonHeapMemory");
        MemoryUsage nonHeapMemory = memory.getNonHeapMemoryUsage();
        info = String.format("init：%s\t max: %s\t used: %s\t committed: %s\t use rate: %s",
                nonHeapMemory.getInit() / MB + "MB",
                nonHeapMemory.getMax() / MB + "MB",
                nonHeapMemory.getUsed() / MB + "MB",
                nonHeapMemory.getCommitted() / MB + "MB",
                nonHeapMemory.getUsed() * 100 / nonHeapMemory.getCommitted() + "%");
        System.out.println(info);
    }

    // 打印GC信息
   public static void printGCInfo(){
        List<GarbageCollectorMXBean> garbageCollectorList = ManagementFactory.getGarbageCollectorMXBeans();
        System.out.println("GC INFO");
        for (GarbageCollectorMXBean garbageCollector: garbageCollectorList) {
            String info = String.format("name: %s\t count: %s\t took: %s\t pool name: %s",
                    garbageCollector.getName(),
                    garbageCollector.getCollectionCount(),
                    garbageCollector.getCollectionTime(),
                    Arrays.deepToString(garbageCollector.getMemoryPoolNames()));
            System.out.println(info);
        }
       System.out.println("-------------------------------------------");
    }
}
